package models

import  (
    "github.com/astaxie/beego/orm"
)

type User struct {
    Id int
    Username string
    Password string
    StudentInfo *StudentInfo `orm:"reverse(one)"`
}

type StudentInfo struct {
    Id int
    User *User `orm:"rel(one)"`
    SchoolNum string `orm:"unique"`
    certificate string
}

func init(){
    orm.RegisterModel(new(User), new(StudentInfo))
}







package main

import (
    "github.com/astaxie/beego"
    _ "myproject/routers"
    "github.com/astaxie/beego/orm"
    _ "github.com/go-sql-driver/mysql"
    // 注意这一步不要忘记了，使用mysql的时候一定要引入驱动
)

func init(){
    orm.RegisterDriver("mysql", orm.DRMySQL)
    orm.RegisterDataBase("default", "mysql", "root:@tcp(127.0.0.1:3306)/test?charset=utf8")
    // 会将model中注册的表在数据库中创建
    orm.RunSyncdb("default", false, true)
}
func main() {
    beego.Run()
}





package controllers

import (
    "github.com/astaxie/beego"
    _ "myproject/models"
    //　注意我们此时还没有使用models包，只需要执行init函数即可，要加上下划线
)

type MainController struct {
    beego.Controller
}
......省略......








package models

import (
    "github.com/astaxie/beego/orm"
)

type User struct {
    Id          int
    Username    string
    Password    string
    StudentInfo *StudentInfo `orm:"reverse(one);null"`
    Posts       []*Post      `orm:"reverse(many)"`
}

// 帖子
type Post struct {
    Id      int
    Content string
    User    *User  `orm:"rel(fk)"`
    Tags    []*Tag `orm:"rel(m2m)"`
}

type StudentInfo struct {
    Id   int
    User *User `orm:"rel(one)"`

    SchoolNum   string `orm:"unique"`
    certificate string
}

type Tag struct {
    Id    int
    Name  string
    Posts []*Post `orm:"reverse(many)"`
}

func init() {
    orm.RegisterModel(new(User), new(StudentInfo), new(Post), new(Tag))
}


mysql -u root
drop database test;
create database test;





